// src/views/login/Index.tsx
import { Form, Input, Button, message } from 'antd'
import {
  UserOutlined,
  LockOutlined
} from '@ant-design/icons';
import { useLocation, useNavigate } from 'react-router-dom'
// 导入封装好的接口
import { IAdminParams, adminLoginFn } from '../../api/user';
// 导入 RTK 相关基础操作信息
import { useAppDispatch } from '../../store/hooks';
import { changeAdminName, changeCheckedkeys, changeLoginState, changeRole, changeToken } from '../../store/modules/user';

type IndexProps = {}


const Index = (props: IndexProps) => {

  // 拿到 redux 中的方法
  const dispatch = useAppDispatch()
  const navigate = useNavigate()

  const { search } = useLocation()
  console.log(search.split('?r=')[1]);
  const redirectUrl = search.split('?r=')[1]



  const onFinish = async (values: IAdminParams) => {
    console.log(values)
    const res = await adminLoginFn(values);
    console.log(res);
    switch (res.data.code) {
      case '10005':
        message.error('不存在该账户')
        break;
      case '10003':
        message.error('密码错误')
        break;
      default:
        message.success('登录成功')
        // 在 RTK 中存储信息到本地进行状态管理
        const result = res.data.data
        dispatch(changeLoginState(true))
        dispatch(changeAdminName(result.adminname))
        dispatch(changeToken(result.token))
        dispatch(changeRole(result.role))
        dispatch(changeCheckedkeys(result.checkedkeys))
        // 应该要跳转到系统首页
        redirectUrl ? navigate(redirectUrl, { replace: false }) : navigate('/', { replace: true })
        break;
    }

  }
  return (
    <div id='components-form-demo-normal-login'>
      <Form
        name="normal_login"
        className="login-form"
        initialValues={{ remember: true }}
        onFinish={onFinish}
      >
        <h1>嗨购管理系统</h1>
        {/* 一定要记得把原来组件库的userName改成 adminname */}
        <Form.Item
          name="adminname"
          rules={[{ required: true, message: '请输入管理员账户!' }]}
        >
          <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="管理员账户" allowClear />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[{ required: true, message: '请输入密码!' }]}
        >
          <Input
            prefix={<LockOutlined className="site-form-item-icon" />}
            type="password"
            placeholder="密码"
            allowClear
          />
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit" className="login-form-button">
            登 录
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}
export default Index